"""
下载视图模块 - PyQt5版本
提供固件文件选择、下载进度显示和日志查看功能
"""
import os
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGroupBox, 
                             QPushButton, QLabel, QProgressBar, QTextEdit,
                             QFileDialog, QFrame, QSizePolicy)
from PyQt5.QtCore import pyqtSignal, Qt, QTimer
from PyQt5.QtGui import QFont, QPalette


class DownloadView(QWidget):
    """下载视图类 - PyQt5版本"""
    
    # 信号定义
    file_selected = pyqtSignal(str)  # 文件选择信号
    download_requested = pyqtSignal(str)  # 开始下载信号
    download_stopped = pyqtSignal()  # 停止下载信号
    
    def __init__(self, parent=None):
        """初始化下载视图"""
        super().__init__(parent)
        
        # 界面状态
        self._current_file_path = ""
        self._download_status = "idle"  # idle, downloading, completed, failed
        
        # 界面组件
        self._file_label = None
        self._size_label = None
        self._progress_bar = None
        self._progress_label = None
        self._download_btn = None
        self._stop_btn = None
        self._log_text = None
        
        # 创建界面
        self._setup_ui()
        
        # 设置初始状态
        self._update_button_states()
    
    def _setup_ui(self):
        """设置用户界面"""
        layout = QVBoxLayout()
        layout.setSpacing(10)
        layout.setContentsMargins(5, 5, 5, 5)
        self.setLayout(layout)
        
        # 固件文件选择区域
        file_group = self._create_file_selection_group()
        layout.addWidget(file_group)
        
        # 下载进度区域
        progress_group = self._create_progress_group()
        layout.addWidget(progress_group)
        
        # 操作按钮区域
        button_layout = self._create_button_layout()
        layout.addLayout(button_layout)
        
        # 日志显示区域
        log_group = self._create_log_group()
        layout.addWidget(log_group)
        
        # 设置比例
        layout.setStretchFactor(file_group, 0)
        layout.setStretchFactor(progress_group, 0)
        layout.setStretchFactor(log_group, 1)
    
    def _create_file_selection_group(self):
        """创建文件选择组"""
        group = QGroupBox("固件文件")
        layout = QVBoxLayout()
        group.setLayout(layout)
        
        # 文件选择按钮
        file_layout = QHBoxLayout()
        
        select_btn = QPushButton("选择文件...")
        select_btn.setFixedWidth(100)
        select_btn.clicked.connect(self._on_select_file)
        file_layout.addWidget(select_btn)
        
        self._file_label = QLabel("未选择文件")
        self._file_label.setStyleSheet("color: #7f8c8d; font-style: italic;")
        file_layout.addWidget(self._file_label)
        
        file_layout.addStretch()
        layout.addLayout(file_layout)
        
        # 文件信息
        info_layout = QHBoxLayout()
        
        size_title = QLabel("文件大小:")
        size_title.setFixedWidth(60)
        info_layout.addWidget(size_title)
        
        self._size_label = QLabel("-")
        self._size_label.setStyleSheet("color: #2c3e50;")
        info_layout.addWidget(self._size_label)
        
        info_layout.addStretch()
        layout.addLayout(info_layout)
        
        return group
    
    def _create_progress_group(self):
        """创建进度显示组"""
        group = QGroupBox("下载进度")
        layout = QVBoxLayout()
        group.setLayout(layout)
        
        # 进度条
        self._progress_bar = QProgressBar()
        self._progress_bar.setRange(0, 100)
        self._progress_bar.setValue(0)
        self._progress_bar.setStyleSheet("""
            QProgressBar {
                border: 1px solid #bdc3c7;
                border-radius: 5px;
                text-align: center;
                font-weight: bold;
            }
            QProgressBar::chunk {
                background-color: #3498db;
                border-radius: 4px;
            }
        """)
        layout.addWidget(self._progress_bar)
        
        # 进度说明
        self._progress_label = QLabel("准备就绪")
        self._progress_label.setAlignment(Qt.AlignCenter)
        self._progress_label.setStyleSheet("color: #7f8c8d; font-size: 12px;")
        layout.addWidget(self._progress_label)
        
        return group
    
    def _create_button_layout(self):
        """创建按钮布局"""
        layout = QHBoxLayout()
        
        # 下载按钮
        self._download_btn = QPushButton("开始下载")
        self._download_btn.setFixedHeight(35)
        self._download_btn.setStyleSheet("""
            QPushButton {
                background-color: #27ae60;
                color: white;
                border: none;
                border-radius: 5px;
                font-weight: bold;
                font-size: 13px;
            }
            QPushButton:hover {
                background-color: #2ecc71;
            }
            QPushButton:pressed {
                background-color: #229954;
            }
            QPushButton:disabled {
                background-color: #bdc3c7;
                color: #7f8c8d;
            }
        """)
        self._download_btn.clicked.connect(self._on_start_download)
        layout.addWidget(self._download_btn)
        
        # 停止按钮
        self._stop_btn = QPushButton("停止下载")
        self._stop_btn.setFixedHeight(35)
        self._stop_btn.setStyleSheet("""
            QPushButton {
                background-color: #e74c3c;
                color: white;
                border: none;
                border-radius: 5px;
                font-weight: bold;
                font-size: 13px;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
            QPushButton:pressed {
                background-color: #a93226;
            }
            QPushButton:disabled {
                background-color: #bdc3c7;
                color: #7f8c8d;
            }
        """)
        self._stop_btn.clicked.connect(self._on_stop_download)
        layout.addWidget(self._stop_btn)
        
        layout.addStretch()
        
        return layout
    
    def _create_log_group(self):
        """创建日志显示组"""
        group = QGroupBox("下载日志")
        layout = QVBoxLayout()
        group.setLayout(layout)
        
        # 日志文本框
        self._log_text = QTextEdit()
        self._log_text.setReadOnly(True)
        
        # 尝试设置最大行数限制（某些PyQt5版本可能不支持）
        try:
            self._log_text.setMaximumBlockCount(1000)
        except AttributeError:
            # 如果不支持，我们会在add_log方法中手动控制行数
            pass
        
        # 设置字体
        font = QFont("Consolas", 9)
        if not font.exactMatch():
            font = QFont("Monaco", 9)
        if not font.exactMatch():
            font = QFont("Courier New", 9)
        self._log_text.setFont(font)
        
        # 设置样式
        self._log_text.setStyleSheet("""
            QTextEdit {
                background-color: #2c3e50;
                color: #ecf0f1;
                border: 1px solid #34495e;
                border-radius: 5px;
                padding: 5px;
            }
        """)
        
        layout.addWidget(self._log_text)
        
        # 清空日志按钮
        clear_layout = QHBoxLayout()
        clear_layout.addStretch()
        
        clear_btn = QPushButton("清空日志")
        clear_btn.setFixedWidth(80)
        clear_btn.clicked.connect(self._clear_log)
        clear_layout.addWidget(clear_btn)
        
        layout.addLayout(clear_layout)
        
        return group
    
    def _on_select_file(self):
        """文件选择事件处理"""
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择固件文件",
            "",
            "固件文件 (*.s19);;所有文件 (*.*)"
        )
        
        if file_path:
            self._current_file_path = file_path
            file_name = os.path.basename(file_path)
            self._file_label.setText(file_name)
            self._file_label.setStyleSheet("color: #2c3e50; font-weight: bold;")
            
            # 发送文件选择信号
            self.file_selected.emit(file_path)
            
            # 更新按钮状态
            self._update_button_states()
    
    def _on_start_download(self):
        """开始下载事件处理"""
        if self._current_file_path:
            self.download_requested.emit(self._current_file_path)
    
    def _on_stop_download(self):
        """停止下载事件处理"""
        self.download_stopped.emit()
    
    def _clear_log(self):
        """清空日志"""
        self._log_text.clear()
    
    def _update_button_states(self):
        """更新按钮状态"""
        has_file = bool(self._current_file_path)
        is_downloading = self._download_status == "downloading"
        
        self._download_btn.setEnabled(has_file and not is_downloading)
        self._stop_btn.setEnabled(is_downloading)
    
    def set_firmware_info(self, info):
        """设置固件信息
        
        Args:
            info: 包含file_name和file_size的字典
        """
        if 'file_name' in info:
            self._file_label.setText(info['file_name'])
            self._file_label.setStyleSheet("color: #2c3e50; font-weight: bold;")
        
        if 'file_size' in info:
            size_mb = info['file_size'] / (1024 * 1024)
            if size_mb >= 1:
                size_text = f"{size_mb:.2f} MB"
            else:
                size_kb = info['file_size'] / 1024
                size_text = f"{size_kb:.1f} KB"
            self._size_label.setText(size_text)
    
    def set_progress(self, percentage, message=""):
        """设置下载进度
        
        Args:
            percentage: 进度百分比 (0-100)
            message: 进度消息
        """
        self._progress_bar.setValue(int(percentage))
        
        if message:
            self._progress_label.setText(message)
        else:
            self._progress_label.setText(f"进度: {percentage:.1f}%")
    
    def set_download_status(self, status):
        """设置下载状态
        
        Args:
            status: 下载状态 ("idle", "downloading", "completed", "failed")
        """
        self._download_status = status
        
        if status == "downloading":
            self._download_btn.setText("下载中...")
            self._progress_bar.setStyleSheet("""
                QProgressBar {
                    border: 1px solid #bdc3c7;
                    border-radius: 5px;
                    text-align: center;
                    font-weight: bold;
                }
                QProgressBar::chunk {
                    background-color: #3498db;
                    border-radius: 4px;
                }
            """)
        elif status == "completed":
            self._download_btn.setText("下载完成")
            self._progress_bar.setStyleSheet("""
                QProgressBar {
                    border: 1px solid #bdc3c7;
                    border-radius: 5px;
                    text-align: center;
                    font-weight: bold;
                }
                QProgressBar::chunk {
                    background-color: #27ae60;
                    border-radius: 4px;
                }
            """)
            # 3秒后重置按钮状态
            QTimer.singleShot(3000, lambda: self._download_btn.setText("开始下载"))
        elif status == "failed":
            self._download_btn.setText("下载失败")
            self._progress_bar.setStyleSheet("""
                QProgressBar {
                    border: 1px solid #bdc3c7;
                    border-radius: 5px;
                    text-align: center;
                    font-weight: bold;
                }
                QProgressBar::chunk {
                    background-color: #e74c3c;
                    border-radius: 4px;
                }
            """)
            # 3秒后重置按钮状态
            QTimer.singleShot(3000, lambda: self._download_btn.setText("开始下载"))
        else:  # idle
            self._download_btn.setText("开始下载")
            self._progress_bar.setStyleSheet("""
                QProgressBar {
                    border: 1px solid #bdc3c7;
                    border-radius: 5px;
                    text-align: center;
                    font-weight: bold;
                }
                QProgressBar::chunk {
                    background-color: #3498db;
                    border-radius: 4px;
                }
            """)
        
        self._update_button_states()
    
    def add_log(self, message):
        """添加日志消息
        
        Args:
            message: 日志消息
        """
        self._log_text.append(message)
        
        # 手动控制日志行数（如果setMaximumBlockCount不可用）
        try:
            # 检查是否已经有setMaximumBlockCount方法
            if not hasattr(self._log_text, 'maximumBlockCount') or self._log_text.maximumBlockCount() == 0:
                # 手动限制行数到1000行
                document = self._log_text.document()
                if document.blockCount() > 1000:
                    cursor = self._log_text.textCursor()
                    cursor.movePosition(cursor.Start)
                    cursor.movePosition(cursor.Down, cursor.KeepAnchor, document.blockCount() - 1000)
                    cursor.removeSelectedText()
        except:
            # 如果出现任何错误，忽略行数限制
            pass
        
        # 自动滚动到底部
        scrollbar = self._log_text.verticalScrollBar()
        scrollbar.setValue(scrollbar.maximum())
    
    def clear_log(self):
        """清空日志"""
        self._log_text.clear()
    
    def reset_progress(self):
        """重置进度"""
        self.set_progress(0, "准备就绪")
        self.set_download_status("idle")